package com.financing.wap.web.controller.api;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAccountService;
import com.financing.wap.service.IActivitesService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.IRegisterService;
import com.financing.wap.service.ISmsNewService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("apiRegisterController")
@RequestMapping("/api/register")
public class RegisterController extends BaseController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	public ISmsNewService smsNewService;
	
	@Autowired
	private IAccountService accountService;
	
	@Autowired
	private ICheckCodeService checkCodeServiceImpl;
	
	@Autowired
	public IActivitesService activitesService;
	
	@Autowired
	private IRegisterService registerService;
	
	
	@RequestMapping(value = "", method=RequestMethod.GET)
	@ResponseBody
	public ResultMap register(HttpServletRequest request, RegisterDTO register, ModelMap resultmap,HttpServletResponse response){
		log.info("get in register post");
		ResultMap result = new ResultMap();
		//验证码校验
		String platformtype = request.getParameter(Constants._PT);
		//1pc,2app ,默认pc
		try{
			//
			if(StringUtils.isBlank(register.getMobile())||StringUtils.isBlank(register.getPassword())){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("手机号或密码为空!");
				return result;
			}
			Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
			
			if(checkCodeServiceImpl.CheckCodeSwitch() && checkOtpCodeTimeOut(register.getMobile(),activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
				result.setMessage("手机验证码超时！");
				return result;
				
			};
			
			if(userService.isMobileRegistered(register.getMobile())){
				log.info("repeat mobile no");
				//已经被注册
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_CONFLICT);
				result.setMessage("手机号码已经被注册！");
				return result;
			}else if(checkCodeServiceImpl.CheckCodeSwitch() && register != null && !register.getvCode().equalsIgnoreCase(getOtpCode(register.getMobile()))){
				log.info("error otpcode");
				//校验验证码
				//未通过
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR);
				result.setMessage("手机验证码不正确！");
				return result;
			}else{
				
				//注册
				UserDTO user = registerService.doRegister(register);
				result.setAttribute("uImage", user.getuImage());
				
				//自动登录
				user = userService.getUserByUF(user);
				//活动判断
				user = activityRole(user);
				
				//			Session session = super.getSession(true);
				
				//自动登录  设置session
				autoLogin(request, user);
				
				String token = user.getId();
				try {
					String sessionId = request.getRequestedSessionId();
					token = SecureUtil.encrypt(token).replaceAll("=", "");
					Cookie cookie = new Cookie(Constants._TOKEN, token);
					cookie.setMaxAge(60*60*24*15);
					cookie.setPath("/");
					response.addCookie(cookie);
					//android 
					result.setAttribute("token", token);
					result.setAttribute("phoneid", sessionId);
					MemcacheCacheHelper.mcc.set(token,System.currentTimeMillis());
				} catch (Exception e) {
					log.error("mobile pt create token error!",e);
				}
				
				result.setAttribute("id", user.getId());
				result.setAttribute("statusCode", ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setMessage("注册成功");
				
				return result;
			}
		}catch(Exception e) {
			log.error("==>error RegisterController register:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("注册失败!");
		}
		return result;
	}
	
	/**
	 * 验证码验证
	 */
	
	@RequestMapping(value = "smsVerif")
	@ResponseBody
	public ResultMap smsVerif(HttpServletRequest request, RegisterDTO register, ModelMap resultmap,HttpServletResponse response){
		ResultMap result = new ResultMap();
		//验证码校验
		if(StringUtils.isBlank(register.getMobile())){
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("手机号为空!");
			return result;
		}
		if(userService.isMobileRegistered(register.getMobile())){
			log.info("repeat mobile no");
			//查询来源
			String ly="";
			UserDTO ud = new UserDTO();
			ud.setLoginName(register.getMobile());
			ud = userService.queryUserLoginName(ud);
			
			if(ud!=null && !StringUtils.isBlank(ud.getuFrom())){
				ly=ud.getuFrom();
			}
			
			result.setAttribute("ufrom", ly);
			//已经被注册
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_CONFLICT);
			result.setMessage("手机号码已经被注册！");
		}else{
			result.setAttribute("statusCode", ResultMap.STATUS_CODE_SUCCESS);
			
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("手机号码可以使用！");
		}
		
		return result;
	}
	
	/**
	 * 手机号重复认证接口
	 * @param request
	 * @param register
	 * @return
	 */
	public ResultMap checkReNameMobile(HttpServletRequest request, RegisterDTO register){
		ResultMap result = new ResultMap();
		if(userService.isMobileRegistered(register.getMobile())){
			log.info("repeat mobile no");
			//已经被注册
			result.setAttribute("status", ResultMap.STATUS_CODE_MOBILE_NUMBER_CONFLICT);
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_CONFLICT);
			result.setMessage("手机号码已经被注册！");
		}else{
			result.setStatus(ResultMap.STATUS.SUCCESS); 
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("可以注册！");
		}
		return result;
	}
	
	
	//活动通过认证
	public UserDTO activityRole(UserDTO user){
		try {
			//查询是否活动中
			String start= "2016-01-01 00:00:00";
			String end = "2017-10-20 23:59:59";
			//判断时间
			Date inputDate = new Date();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = sf.parse(start);
			Date d2 = sf.parse(end);
			 //在设定时间内 
			if(inputDate.before(d2) && inputDate.after(d1) && (user.getRole()==null || !user.getRole().equals("2"))){
				//修改状态为通过
				UserDTO ud = new UserDTO();
				ud.setId(user.getId());
				ud.setuShoprole("2"); //
				ud.setFpTempRole("1"); //活动通过标识
				user.setRole("2");
				ud.setLoginName(user.getLoginName());
				userService.updateUser(ud);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return user;
	}
	
	
	
	public static void main(String[] args) {
		System.out.println(new SimpleDateFormat("HH:mm;yyyy-MM-dd").format(new Date()).replaceAll(";", "    "));
	}
}
